<?php

namespace App\Http\Controllers;

use App\Repository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ManageController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function addRepository(Request $request)
    {
        if(Auth::id() != 1)
            return abort(403);
        $repo = new Repository();
        $repo->name = $request->input('name');
        $repo->type = $request->input('type');
        $repo->category = $request->input('category');
        if($request->input('type') == 'remote')
            $repo->upstream_url = $request->input('upstream_url');
        else
            $repo->upstream_url = 'null';
        $repo->description = $request->input('description');
        $repo->offline = false;
        $repo->saveOrFail();
        return redirect()->to('/dashboard/repository');
    }

    public function editRepository(Request $request, $name)
    {
        if(Auth::id() != 1)
            return abort(403);
        $repo = Repository::where('name', $name)->firstOrFail();
        if($request->has('name'))
            $repo->name = $request->input('name');
        if($request->has('type'))
            $repo->type = $request->input('type');
        if($request->has('category'))
            $repo->category = $request->input('category');
        if($request->has('upstream_url'))
            $repo->upstream_url = $request->input('upstream_url');
        if($request->has('description'))
            $repo->description = $request->input('description');
        if($request->has('offline'))
            $repo->offline = $request->input('offline');
        $repo->saveOrFail();
        return redirect()->to('/dashboard/repository');
    }
}
